﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data.Common;
using System.Data;
namespace SqlHelper
{
    public class SqlException : ApplicationException
    {
        private static class MessageFormat
        {
            public static string Format(string message,
                string commandText,
                CommandType cmdtype,
                DbParameter[] parameters)
            {
                string text = message + Environment.NewLine
                    + " ---> CommandText: " + commandText + Environment.NewLine
                    + " ---> CommandType: " + cmdtype.ToString() + Environment.NewLine
                    + " ---> DbParameters: " + FormatParameters(parameters);
                return text;
            }

            private static string FormatParameters(DbParameter[] parameters)
            {
                if (parameters == null || parameters.Length == 0) return "";
                StringBuilder sb = new StringBuilder();
                foreach (var p in parameters)
                {
                    if (sb.Length > 0) sb.AppendLine();
                    sb.AppendFormat("{0}[ParameterName:{1},DbType:{2},Size:{3},Direction:{4}]"
                        , p.ParameterName, p.Value, p.DbType, p.Size, p.Direction);
                }
                return sb.ToString();
            }
        }

        public SqlException()
            : base()
        {
        }

        public SqlException(string message,
            Exception innerException,
            string commandText,
            CommandType cmdtype,
            DbParameter[] parameters)
            : base(MessageFormat.Format(message, commandText, cmdtype, parameters), innerException)
        {
            CommandText = commandText;
            CommandType = cmdtype;
            Parameters = parameters;
        }

        public string CommandText { get; private set; }

        public CommandType CommandType { get; private set; }

        public DbParameter[] Parameters { get; private set; }
    }
}
